package com.zhou.base.resilience4j.test.util;

import com.zhou.base.resilience4j.test.entity.SystemLog;
import io.github.resilience4j.bulkhead.BulkheadFullException;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

@Slf4j
@Component
public class RateLimiterServiceImpl {

    @Autowired
    private RemoteServiceConnector remoteServiceConnector;

    @Autowired
    private RateLimiterRegistry rateLimiterRegistry;

    public List<SystemLog> ratelimiterNotAOP() {
        // 通过注册器获得RateLimiter实例
        RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter("backendA");
        RateLimiterUtil.getRateLimiterStatus("开始执行前: ", rateLimiter);
        // 通过Try.of().recover()调用装饰后的服务
        Try<List<SystemLog>> result = Try.of(
                RateLimiter.decorateCheckedSupplier(rateLimiter, remoteServiceConnector::process))
                .recover(BulkheadFullException.class, throwable -> {
                    log.info("服务失败: " + throwable.getLocalizedMessage());
                    return new ArrayList();
                });
        RateLimiterUtil.getRateLimiterStatus("执行结束: ", rateLimiter);
        return result.get();
    }

    public List<SystemLog> rateLimiterAOP() throws TimeoutException, InterruptedException {
        List<SystemLog> result = remoteServiceConnector.processRateLimite();
        RateLimiterUtil.getRateLimiterStatus("执行结束：", rateLimiterRegistry.rateLimiter("backendA"));
        return result;
    }
}
